package cn.tedu.v2_1;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 *  聊天室 Version 2.1
 *  客户端基本不变：关闭socket，拓展增加IP
 *                          1.私有化IP
 *                          2.构造器，当前IP进行赋值
 *                          3.任意位置使用IP[读入知道对方IP]
 *
 */
public class Client {
    private Socket socket;
    //1.私有化IP
    private String ip;
    public Client(){
        try {
            socket =new Socket("127.0.1.0",9908);
            //2.确定传入IP就是当前IP地址
            ip=socket.getInetAddress().getHostAddress();
        }catch (SocketException e) {
            System.out.println("连接被重置");
        }catch (UnknownHostException e) {  //用户地址出问题了（异常）
            System.out.println("IP地址有问题，请询问服务器端！");
        }
        catch (IOException e) { //IO异常：连接失效，客户端主动退出了
            System.out.println("客户端主动退出了：断开连接");
        }
    }
    public void start() {
        PrintWriter pw=null;//置空流

        try {
            pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);
            System.out.println("客户端用户：请输入文字：");
            Scanner input=new Scanner(System.in);//测试--控制台输入文本
            while(true){  //死循环---一直与服务器说话
                String say=input.nextLine();
                pw.println("客户端说"+say);    //写出一行行文字
                System.out.println("写出完毕");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端：字符集不一致");
        }catch (IOException e) {
            System.out.println("客户端断开了连接！");
        } finally {

            if (pw!=null)
                pw.close();
            System.out.println("打印流关闭");
            if (socket!=null&&!socket.isClosed()){
                System.out.println("客户端关闭成功!");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败~");
                }
            }
        }
    }
    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }
}
